<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="课题名称" name="subject_name">
      <a-select
        v-model:value="ruleForm.subject_name"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in SubjectNameSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="实验名称" name="experiment_name">
      <a-select
        v-model:value="ruleForm.experiment_name"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in ExperimentNameSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in AlloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="英文名称" name="english_name">
      <a-input v-model:value="ruleForm.english_name" />
    </a-form-item>
    <a-form-item label="别名" name="alias">
      <a-input v-model:value="ruleForm.alias" />
    </a-form-item>
    <a-form-item label="生产单位" name="production_unit">
      <a-input v-model:value="ruleForm.production_unit" />
    </a-form-item>
    <a-form-item label="应用概况" name="application_overview">
      <a-input v-model:value="ruleForm.application_overview" />
    </a-form-item>
    <a-form-item label="数据来源" name="data_source">
      <a-input v-model:value="ruleForm.data_source" />
    </a-form-item>

    <a-form-item label="数据来源附件" name="data_source_attachment">
      <a-upload
        :fileList="ruleForm.DataSourceAttachmentFileList"
        :beforeUpload="beforeDataSourceAttachmentUpload"
        :headers="headers"
        @change="handleDataSourceAttachmentChange"
      >
        <a-button> <upload-outlined /> 选择 </a-button>
      </a-upload>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'

export default {
  name: 'AddOrEditSampleInfo',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  components: {
    UploadOutlined,
  },
  data() {
    // validStr不包含空格
    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateSubjectName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择课题名");
      }
    };
    let validateExperimentName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择实验名");
      }
    };
    let validateAlloyCode = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择合金代码");
      }
    };
    let validateSampleName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请填写样品名称");
      }else {
        if (!isValidStr(value)) {
          return Promise.reject("样品名称含有非法字符")
        }
        return Promise.resolve();
      }
    };

    return {
      ruleForm: {
        subject_name: '',
        experiment_name: '',
        alloy_code: '',
        sample_name: '',
        english_name: '',
        alias: '',
        production_unit: '',
        application_overview: '',
        data_source: '',
        DataSourceAttachmentFileList: [],
      },

      rules:{
        subject_name: [
          {
            validator: validateSubjectName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        experiment_name: [
          {
            validator: validateExperimentName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        alloy_code: [
          {
            validator: validateAlloyCode,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        sample_name: [
          {
            validator: validateSampleName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },


      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },

      submitting: false,

      SubjectNameSelectionOptions: [],
      ExperimentNameSelectionOptions: [],
      AlloyCodeSelectionOptions: [],

      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.SubjectNameSelectionOptions = []
      this.ExperimentNameSelectionOptions = []
      this.AlloyCodeSelectionOptions = []
      this.axios
        .get('/subject_management/subjects/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.SubjectNameSelectionOptions.push({
              url: data[i].url,
              label: data[i].subject_name,
            })
          }

        })


      this.axios
        .get('/experiment_management/experiment_information/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.ExperimentNameSelectionOptions.push({
              url: data[i].url,
              label: data[i].experiment_name,
            })
          }

        })

      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.AlloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }

        })


      if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.subject_name = data.subject_name
                this.ruleForm.experiment_name = data.experiment_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.english_name = data.english_name
                this.ruleForm.alias = data.alias
                this.ruleForm.production_unit = data.production_unit
                this.ruleForm.application_overview = data.application_overview
                this.ruleForm.data_source = data.data_source
                //数据来源附件文件
                if (data.data_source_attachment_filename !== '') {
                  // console.log('not null')
                  this.ruleForm.DataSourceAttachmentFileList.push({
                    uid: '-1',
                    name: data.data_source_attachment_filename,
                  })
                }

              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
    },
    handleFinish(values) {
      this.submitting = true
      const {
        DataSourceAttachmentFileList,
      } = this.ruleForm
      const formData = new FormData()
      formData.append('subject_name', values.subject_name)
      formData.append('experiment_name', values.experiment_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('sample_name', values.sample_name)
      formData.append('english_name', values.english_name)
      formData.append('alias', values.alias)
      formData.append('production_unit', values.production_unit)
      formData.append('application_overview', values.application_overview)
      formData.append('data_source', values.data_source)
      DataSourceAttachmentFileList.forEach((file) => {
        // 若选择了文件，那么会有originFileObj属性，这种情况直接上传就可以，
        // 若无originFileObj属性，则说明是在编辑，且没有更改文件，文件列表中只有文件名而无文件实体，
        // 这个时候不传文件参数，让后端保持原文件不变
        if ('originFileObj' in file) {
          formData.append('data_source_attachment', file.originFileObj)
        }
      })

      if (this.url !== '') {
        if (this.ruleForm.DataSourceAttachmentFileList.length === 0) {
          formData.append('data_source_attachment_empty', true)
        }
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/sample_info/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
    beforeDataSourceAttachmentUpload(file) {
      this.ruleForm.DataSourceAttachmentFileList = [
        ...this.ruleForm.DataSourceAttachmentFileList,
        file,
      ]
      return false
    },
    handleDataSourceAttachmentChange(info) {
      let fileList = [...info.fileList]
      // 取最后选择的文件
      fileList = fileList.slice(-1)
      this.ruleForm.DataSourceAttachmentFileList = fileList
    },
  },
}
</script>
